﻿(function (winjs, mvvmStack) {
    "use strict";

    var SectionViewModel = winjs.Class.derive(mvvmStack.ViewModelBase, function (applicationController, imageService) {
        this.id = applicationController.selectedHomeSection;
        this.sectionTitle = "Sezione " + this.id;
        this._imageService = imageService;
        this.images = new winjs.Binding.List();
        this.currentPage = winjs.Binding.as({
            value: 0
        });

        this.processAll();
        
        //Watch for currentpage property changes and updates commands availability
        this.watch(this.currentPage, "value", this.onCurrentPageChanged);
    },
    {
        sectionTitle: null,
        images: null,
        currentPage: null,
        id: 0,
        load: function () {
            var self = this;
            this._imageService.load(self.id).then(function (photos) {
                photos.forEach(function (photoInfo) {
                    self.images.push(photoInfo);
                });
            });

            this.onCurrentPageChanged(this.currentPage.value);
        },
        firstCommand: new mvvmStack.RelayCommand(function (element) {
            this.currentPage.value = 0;
            this.firstCommand.canExecute.value = false;
            this.lastCommand.canExecute.value = true;
        }),
        lastCommand: new mvvmStack.RelayCommand(function (element) {
            this.currentPage.value = this.images.length - 1;
            this.firstCommand.canExecute.value = true;
            this.lastCommand.canExecute.value = false;
        }),
        serialize: function () {
            return {
                currentPage: this.currentPage.value
            };
        },
        hydrate: function (bag) {
            this.currentPage.value = bag.viewModels.sectionViewModel.currentPage;
        },
        onCurrentPageChanged: function (page) {
            this.firstCommand.canExecute.value = page !== 0;
            this.lastCommand.canExecute.value = this.images.length > 0 && page != this.images.length - 1;
        },
        onAppResuming: function () {
            console.log("SectionViewModel notified that app has been resumed.")
        }
    });

    winjs.Namespace.define("Demo.ViewModels", {
        SectionViewModel: SectionViewModel
    });

})(WinJS, MvvmStack)